#include "Codepad.hpp"

Codepad::Codepad()
{
  m_request = new HTTPRequest();
}

Codepad::~Codepad()
{
  delete m_request;
}

Snippet* Codepad::CreateSnippet(string code, string language, string description, bool run)
{
  HTTPREQUEST_POST post;
  HTTPREQUEST_DATA data, headers;

  post["lang"]    = m_request->Escape(language);
  post["code"]    = m_request->Escape(code);
  post["private"] = "True";
  post["submit"]  = "Submit";

  if (run)
    post["run"] = "True";

  m_request->Post("http://codepad.org/", post, &data, &headers);

  string headerData = string(headers.begin(), headers.end());
  char_separator<char> delimiter("\n");
  tokenizer<char_separator<char> > tokens(headerData, delimiter);

  for (tokenizer<char_separator<char> >::iterator i = tokens.begin(); i != tokens.end(); i++)
  {
    string search = "Location: http://codepad.org/";

    if (i->find(search) == 0)
    {
      Snippet* ret = new Snippet;

      // fill snippet ID - cut off last '\n'
      ret->m_snippetId = i->substr(search.length(), i->length() - search.length() - 1); 

      // fill other details
      ret->m_description  = description;
      ret->m_language     = language;

      return ret;
    }
  }
  return NULL;
}